package com.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.util.Page;

//import com.entity.Page;

public class BaseDaoImpl<T> implements BaseDao<T> {
	@Autowired
	public SessionFactory sf;
	Class<T> cls;
	public BaseDaoImpl(){
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		Type[] tp = pt.getActualTypeArguments();
		cls=(Class<T>) tp[0];
	}
	@Override
	public void save(T t) {
		sf.getCurrentSession().save(t);
		
	}
	@Override
	public void delete(T t) {
		sf.getCurrentSession().delete(t);
	}

	@Override
	public void update(T t) {
		sf.getCurrentSession().update(t);
	}

	@Override
	public T get(Serializable id) {
		return (T) sf.getCurrentSession().get(cls, id);
	}

	@Override
	public List<T> getAll() {
		return sf.getCurrentSession().createQuery("from "+cls.getSimpleName()).list();
	}

	@Override
	public Page getPage(T t, Page p,String sql) {
		String hql = "from "+cls.getSimpleName()+" where 1 = 1"+sql;
		Query query = sf.getCurrentSession().createQuery(hql);
		query.setProperties(t);
		query.setFirstResult(p.getStartNum());
		query.setMaxResults(p.getPageSize());
		List<T> list = query.list();
		p.setList(list);
		Query query1 = sf.getCurrentSession().createQuery(hql);
		query1.setProperties(t);
		List<T> list1 = query1.list();
		p.setTotalCount(list1.size());
		return p;
	}
	
	
	@Override
	public List<T> getByHql(String hql, Map obj) {
		Query query = sf.getCurrentSession().createQuery(hql);
		if(obj != null)
			query.setProperties(obj);
		return query.list();
	}
	@Override
	public Page getPageByHql(String hql, Map obj, Page p) {
		Query query = sf.getCurrentSession().createQuery(hql);
		if(obj != null)
			query.setProperties(obj);
		query.setFirstResult(p.getStartNum());
		query.setMaxResults(p.getPageSize());
		p.setList(query.list());
		query =  sf.getCurrentSession().createQuery(hql);
		if(obj != null)
			query.setProperties(obj);
		p.setTotalCount(query.list().size());
		return p;
	}
}
